import store from '@/store'
import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw} from 'vue-router'
// import {moduleComp} from '@/libs/defineComponent'

const whiteList = ['/'] // 白名单 无需校验

// 默认路由
export const defaultRoutes: RouteRecordRaw[] = [
  {
    path: '/:pathMatch(.*)',
    redirect: '/404'
  },
  {
    path: '/',
    redirect: '/myPerformance'
  },
  {
    path: '/404',
    name: '404',
    component: import('../views/404/404')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  // routes: defaultRoutes.concat(asyncRouters)
  routes: defaultRoutes
})

router.beforeEach(async (to, from, next) => {
  // 校验用户权限组
  // 当页面刷新 或者初次打开时首次获取用户组为null
  let userRoles = store.getters['login/GETROLES']

  if (!userRoles || userRoles.includes(0)) {
    if (whiteList.includes(to.path)) {
      console.log('白名单路由，直接前往', to)
      return next()
    }

    let userInfo = await store.dispatch('login/GetUserInfo').catch(err => {
      console.log('用户信息加载失败', err)
    })

    if (!userInfo) return next()

    console.log('用户信息', userInfo)

    let roles = userInfo.userRoles

    if (!roles || roles.includes(0)) {
      // 获取到的roles为null,或者权限中包含0时，认证失败

      console.log('用户历史登录信息获取失败')

      return next()
    } else {
      // 权限认证成功

      let res = await store.dispatch('login/GenerateRoutes').catch(err => {})

      if (!res) return next()

      console.log('即将前往路由', to, '前一个路由', from)

      return next(to.redirectedFrom ? to.redirectedFrom : to.path)
    }
  } else {
    console.log(`用户权限正常，从${from.path}, 跳转至${to.path}`, to, location.href)

    // 在跳转页面的时候，判断是否存在参数

    // 权限组有数据直接跳转路由
    return next()
  }
})

console.log('初始路由', router.getRoutes())

export default router
